package com.demo.action;

import com.demo.domain.Customer;
import com.demo.service.CustomerService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import java.util.List;

public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {

    private Customer customer = new Customer();
    private CustomerService customerService;

    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }

    //添加
    public String add() throws Exception {

        customerService.saveCustomer(customer);
        return "saveSuccess";

    }

    // 查找客户列表
    public String list() throws Exception {
        List<Customer> list = customerService.find();
        ActionContext.getContext().getValueStack().set("list", list);
        return "Customer_findSuccess";
    }

    // 删除的方法
    public String delete() {
        // 使用模型驱动获取表单提交cid值
        int cid = customer.getCust_id();
        // 删除规范操作：先查询，再删除（级联表会有影响）
        Customer c = customerService.findOne(cid);
        // 调用方法删除
        if (c != null) {
            customerService.delete(c);
        }
        return "delete";
    }

    // 通过id修改 跳转到修改页面
    public String showCustomer() throws Exception {
        Integer cid = customer.getCust_id();
        Customer c = customerService.findOne(cid);
        ServletActionContext.getRequest().setAttribute("customer", c);
        return "showCustomer";
    }

    //修改用户
    public String update() {
        customerService.update(customer);
        return "Customer_updateSuccess";
    }

    // 条件查询
//    public String listcondition() throws Exception {
//        // 有输入客户名就根据客户名查询
//        // 没有输人就查询所有
//        if (customer.getCust_name() != null
//                && customer.getCust_name().equals(customer.getCust_name())) {
//
//            List<Customer> list = customerService.findCondition(customer);
//
//        } else {
//            customerService.find();
//        }
//        return "listcondition";
//    }

    // 到修改客户页面
    public String toSelectCustomerPage() {

        return "toSelectCustomerPage";
    }

    // 多条件查询
    public String moreCondition() throws Exception {

        List<Customer> list = customerService.findMoreCondition(customer);

        ActionContext.getContext().put("list", list);
        return "moreCondition";
    }


    @Override
    public Customer getModel() {
        return customer;
    }
}
